import axios from 'axios';

// 创建Axios实例
const api = axios.create({
  baseURL: 'http://localhost:3003/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证信息等
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 统一错误处理
    console.error(`API Error: ${error.config.method.toUpperCase()} ${error.config.url} - Status: ${error.response?.status || 'Network Error'}`, error.response?.data || error.message);
    return Promise.reject(error);
  }
);

// 导出API方法
export default {
  // 排班类型相关API
  shiftTypes: {
    getAll: () => api.get('/shift-types'),
    getById: (id) => api.get(`/shift-types/${id}`),
    create: (data) => api.post('/shift-types', data),
    update: (id, data) => api.put(`/shift-types/${id}`, data),
    delete: (id) => api.delete(`/shift-types/${id}`)
  },
  // 人员相关API
  employees: {
    getAll: () => api.get('/employees'),
    getById: (id) => api.get(`/employees/${id}`),
    create: (data) => api.post('/employees', data),
    update: (id, data) => api.put(`/employees/${id}`, data),
    delete: (id) => api.delete(`/employees/${id}`),
    getByType: (type) => api.get(`/employees/getByType/${type}`)
  },
  // 节假日相关API
  holidays: {
    getByRange: (startDate, endDate) => api.get(`/holidays?start=${startDate}&end=${endDate}`)
  },

  // 排班相关API
  schedules: {
    getAll: (params) => api.get('/schedules', { params }),
    getById: (id) => api.get(`/schedules/${id}`),
    create: (data) => api.post('/schedules', data),
    update: (id, data) => api.put(`/schedules/${id}`, data),
    delete: (id) => api.delete(`/schedules/${id}`),
    generate: (data) => api.post('/schedules/generate', data),
    getByRange: (startDate, endDate) => api.get(`/schedules?start=${startDate}&end=${endDate}`),
    export: (startDate, endDate) => api.get(`/schedules/export?start=${startDate}&end=${endDate}`, { responseType: 'blob' }),
    // 根据月份获取排班数据
    getByMonth: (year, month) => {
      // 计算月份的第一天和最后一天
      const startDate = new Date(year, month - 1, 1).toISOString().split('T')[0];
      const endDate = new Date(year, month, 0).toISOString().split('T')[0];
      return api.get(`/schedules?start=${startDate}&end=${endDate}`);
    },
    // 根据员工ID和月份获取排班
    getByEmployeeAndMonth: (employeeId, year, month) => api.get(`/schedules/getByEmployeeAndMonth/${employeeId}/${year}/${month}`),
    // 换班操作
    swapShifts: (scheduleId1, scheduleId2) => api.post('/schedules/swapShifts', { scheduleId1, scheduleId2 })
  }
};